package com.example.openim.service.impl;

import com.example.openim.domain.OrgData;
import com.example.openim.service.OrgQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * @description:
 * @author: ZhangHuixin
 * @created: 2025-11-04 10:29:29
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrgQueryServiceImpl implements OrgQueryService {

    private final MongoTemplate mongoTemplate;

    @Override
    public List<OrgData> findOrgs(String zbmId) {

        Query query = new Query();

        // ZSJBMID 条件
        Criteria zsjbmidCriteria;
        if (StringUtils.isEmpty(zbmId)) {
            zbmId = "50000000";
        }
        zsjbmidCriteria = Criteria.where("ZSJBMID").is(zbmId);

        // ZRYDE 条件
        Criteria zrydeCriteria = new Criteria().orOperator(
                Criteria.where("ZRYDE").is(null),
                Criteria.where("ZRYDE").is("")
        );
        // BLOCK 条件
        Criteria blockCriteria = new Criteria().orOperator(
                Criteria.where("BLOCK").is(null),
                Criteria.where("BLOCK").is("")
        );

        // 两个条件 AND 组合
        Criteria finalCriteria = new Criteria().andOperator(zsjbmidCriteria, zrydeCriteria, blockCriteria);

        // 添加到 Query
        query.addCriteria(finalCriteria);
        // 按 ZBMPX 升序排序
        query.with(Sort.by(Sort.Direction.ASC, "ZBMPX"));
        return mongoTemplate.find(query, OrgData.class);

    }
}
